package com.example.controller;

import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;


    @GetMapping("/list")
    public String list(Model model) {
        List<User> users = userService.getAllUsers();
        model.addAttribute("users", users);
        return "user/list";
    }

    @GetMapping("/add")
    public String toAddPage() {
        return "user/add";
    }

    @PostMapping("/add")
    public String add(User user) {
        userService.addUser(user);
        return "redirect:/user/list";
    }

    @GetMapping("/edit/{userid}")
    public String toEditPage(@PathVariable("userid") Integer userid, Model model) {
        User user = userService.getUserById(userid);
        model.addAttribute("user", user);
        return "user/edit";
    }

    @PostMapping("/edit")
    public String edit(User user) {
        userService.updateUser(user);
        return "redirect:/user/list";
    }

    @GetMapping("/delete/{userid}")
    public String delete(@PathVariable("userid") Integer userid) {
        userService.deleteUser(userid);
        return "redirect:/user/list";
    }

    @RequestMapping("/login")
    public String login(String username, String password, HttpServletRequest request) {
        User user = this.userService.getUserByNameAndPassword(username, password);
        if (user == null) {
            return "redirect:/index";
        } else {
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            return "redirect:/user/list";
        }
    }

    // 注册页面（GET请求）
    @GetMapping("/register")
    public String showRegisterForm() {
        return "user/register";
    }

    // 处理注册提交（POST请求）
    @PostMapping("/register")
    public String processRegistration(
            @RequestParam String username,
            @RequestParam String password,
            RedirectAttributes redirectAttributes) {
        // 添加日志记录
        System.out.println("开始处理注册请求，用户名：" + username);

        try {
            // 1. 检查用户名是否已存在
            if (userService.isUsernameExists(username)) {
                redirectAttributes.addFlashAttribute("error", "用户名已存在");
                System.out.println("用户名已存在，重定向到注册页");
                return "redirect:/user/register";
            }

            // 2. 创建新用户
            User newUser = new User();
            newUser.setUsername(username);
            newUser.setPassword(password); // 注意：实际项目这里需要加密

            // 3. 保存用户
            boolean result = userService.addUser(newUser);
            if (!result) {
                redirectAttributes.addFlashAttribute("error", "注册失败，请稍后再试");
                System.out.println("用户添加失败");
                return "redirect:/user/register";
            }

            // 4. 跳转到登录页并显示成功消息
            redirectAttributes.addFlashAttribute("success", "注册成功，请登录");
            System.out.println("注册成功，重定向到登录页");
            return "redirect:/user/login";
        } catch (Exception e) {
            // 捕获异常并记录
            System.err.println("注册处理异常：" + e.getMessage());
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("error", "注册过程中发生错误，请稍后再试");
            return "redirect:/user/register";
        }
    }
}